# -*- coding: utf-8 -*-

# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
import hmac
import time
import hashlib
import requests
import json
import urllib
import copy
import operator
from urllib.request import urlopen, Request

class Bihe():
    _headers = {
    'Content-Type': 'application/json; charset=utf-8',
    'X-BIBR-APIKEY':'0e100CEa92bE41d990670eD69c69f8e0',
	'Accept': 'application/json',
    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'
    }

    def __init__(self, apiKey, secret):
        self.url = 'http://47.104.165.120:8099/openapi' 
        # 'http://47.104.165.120:8099/openapi'  http://47.75.164.146:8099/openapi'
        self.apiKey = apiKey
        self.secret = secret
        
    def get_currency_msg(self,symbol,sjid):
        return self._v1('/v1/exchange/rule?symbol='+symbol+'&merchantId='+sjid, method='get',auth=False)
    
    def get_ticker(self,symbol,sjid):
        return self._v1('/v1/depth?symbol='+symbol+'&merchantId='+sjid, method='get',auth=False)
    
    def get_account(self,Code,sjid):
        return self._v1('/v1/asset/account', method='post', auth=True , coinCode=Code,merchantId=sjid)
    
	
	#取消订单	1次/1秒
    def cancel_order(self, order_id):
        return self._v1('/cancel_order', method='post', auth=True, order_id=order_id, apikey=self.apiKey)
		
    def _v1(self, path, method, auth, **params):
        url = self.url + path
        if auth:
            if not self.apiKey or not self.secret:
                print('API keys not configured!')
            data = dict(params,**self.sign(params))
        else:
            data = params
		
        if method == 'post':
            resp = self.httpPost(url, data)
        else:
            resp = self.httpGet(url)
			
        return self._process_response(resp)
			
    def _process_response(self, resp):

        data = resp
        if data['code'] != 0:
            print(data['message'])
        return data['message'] , data['code']

    def sign(self, params):
        _params = copy.copy(params)
        now = int(time.time()*1000)
        _params['timestamp'] = now
        out = []
        for k, v in _params.items():
            out.append("{}={}".format(str(k).strip(), str(v).strip()))
        out.sort()
        s = "&".join(out)
        _sign = hmac.new(self.secret.encode(), s.encode(), digestmod=hashlib.md5).hexdigest().upper()
        # sort_params = sorted(_params.items(), key=operator.itemgetter(0))
        # sort_params = dict(sort_params)
        # string = urllib.parse.urlencode(sort_params)
        # hash = hashlib.md5()
        # hash.update((s + self.secret).encode('utf-8'))
        # _sign = hash.hexdigest().upper()
        '''
        _params = copy.copy(params)
        now = int(round(time.time()))
        # timeStamp = time.strftime('%Y%m%d%H%M%S',time.localtime(now))
        _params['timestamp'] = int(now)
        sort_params = sorted(_params.items(), key=operator.itemgetter(0))
        sort_params = dict(sort_params)
        # sort_params['secret_key'] = self.secret
        string = urllib.parse.urlencode(sort_params)+self.secret.encode('utf-8')
        _sign = hashlib.md5(bytes(string.encode('utf-8'))).hexdigest().upper()
        '''
        params={}
        params['sign'] = _sign
        params['timestamp'] = now
        return params
		
    def httpGet(self,url):
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}
        request = Request(url=url, headers=headers)
        content = urlopen(request, timeout=15).read()
        content = content.decode('utf-8')
        json_data = json.loads(content)
        return json_data

    def httpPost(self,url, params):
        _headers = self._headers
        temp_params = json.dumps(params)
        dataa = bytes(temp_params, encoding='utf8')
#        headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}  
        request = Request(url=url, data=dataa, headers=_headers)
        content = urlopen(request).read()
        json_data = json.loads(content)
        return json_data


